package com.szyjjk.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szyjjk.entity.RunMapData;
import com.szyjjk.entity.RunProperty;
import org.apache.commons.lang3.StringUtils;
//import org.geotools.data.FeatureWriter;
//import org.geotools.data.Transaction;
//import org.geotools.data.shapefile.ShapefileDataStore;
//import org.geotools.data.shapefile.ShapefileDataStoreFactory;
//import org.geotools.data.simple.SimpleFeatureCollection;
//import org.geotools.data.simple.SimpleFeatureIterator;
//import org.geotools.data.simple.SimpleFeatureSource;
//import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
//import org.geotools.geometry.jts.JTSFactoryFinder;
//import org.geotools.referencing.crs.DefaultGeographicCRS;
//import org.locationtech.jts.geom.Coordinate;
//import org.locationtech.jts.geom.GeometryFactory;
//import org.locationtech.jts.geom.MultiPolygon;
//import org.locationtech.jts.geom.Point;
//import org.locationtech.jts.io.ParseException;
//import org.locationtech.jts.io.WKTReader;
//import org.opengis.feature.simple.SimpleFeature;
//import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @program: szyjjk
 * @description: 操作shp工具类
 * @author: yangyue
 * @create: 2020-09-23 15:37
 */
public class GeoTool {

    /**
     * @return void
     * @Author yangyue
     * @Description //TODO 创建shp文件
     * @Date 9:06 2020/9/25
     * @Param [path, rusltMapArray]
     **/
//    public static void createShp(String path, List<Map<String, String>> rusltMapArray) throws Exception {
//        //1.创建shape文件对象
//        File file = new File(path);
//        if (file.exists()) {
//            file.delete();
//        }
//        Map<String, Serializable> params = new HashMap<>(1);
//        params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
//        //2.创建一个新的数据存储——对于一个还不存在的文件。
//        ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
//        //3.定义图形信息和属性信息
//        //SimpleFeatureTypeBuilder 构造简单特性类型的构造器
//        SimpleFeatureTypeBuilder tBuilder = new SimpleFeatureTypeBuilder();
//        //设置
//        //WGS84:一个二维地理坐标参考系统，使用WGS84数据
//        tBuilder.setCRS(DefaultGeographicCRS.WGS84);
//        tBuilder.setName("shapefile");
//        //添加 一个点
//        tBuilder.add("the_geom", MultiPolygon.class);
//
//        //添加列
//        for (String key : rusltMapArray.get(0).keySet()) {
//            //排除构建数据
//            if (!"geom".equals(key.toString())) {
//                tBuilder.add(key, String.class);
//            }
//        }
//        //添加一个id
//        ds.createSchema(tBuilder.buildFeatureType());
//        //设置编码  utf-8乱码，必须使用GBK
//        ds.setCharset(Charset.forName("GBK"));
//        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(
//                ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
//
//        for (Map<String, String> stringsMap : rusltMapArray) {
//            //创建一个点
//            SimpleFeature feature = writer.next();
//            //X轴坐标
//            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
//            WKTReader reader = new WKTReader(geometryFactory);
////            System.out.println(stringsMap.get("geom"));
//            MultiPolygon p = (MultiPolygon) reader.read(stringsMap.get("geom"));
//            feature.setAttribute("the_geom", p);
//            for (Map.Entry<String, String> entry : stringsMap.entrySet()) {
//                if (!"geom".equals(entry.getKey().toString())) {
//                    //System.out.println("key:"+entry.getKey()+"; value:"+entry.getValue());
//                    feature.setAttribute(entry.getKey(), entry.getValue());
//                }
//
//            }
//        }
//        //写入
//        writer.write();
//        //关闭
//        writer.close();
//        //释放资源
//        ds.dispose();
//    }





    // GeoJSONLayer  json构建
    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Author yangyue
     * @Description //TODO 构建返回前端的json
     * @Date 10:43 2020/11/3
     * @Param [runMapDataArray, tier, pro, runProperty, fileType]
     **/
    public static JSONObject createGeoJSONLayerMap(List<RunMapData> runMapDataArray, String tier, String pro, RunProperty runProperty, int fileType, int ColorType, List<RunMapData> runMapDataArrayDistinct) {
//        runMapDataArray = runMapDataListChangePro(runMapDataArray, pro);
        Map<String, List<String>> changeArrayData = new HashMap<>();
        if (ColorType == 1) {
            changeArrayData = changeArrayData(runMapDataArrayDistinct);
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject metadata = new JSONObject();
        metadata.put("status", "200");
        jsonObject.put("metadata", metadata);
        JSONArray features = new JSONArray();
        for (int i = 0; i < runMapDataArray.size(); i++) {
            RunMapData runMapData = runMapDataArray.get(i);

            JSONObject one = new JSONObject();
            one.put("id", runMapData.getId());
            one.put("type", "Feature");
            JSONObject geometryOne = new JSONObject();
            geometryOne.put("type", "Point");
            String[] longlat = runMapData.getMapSiteXy().split(",");
            geometryOne.put("coordinates", new double[]{Double.parseDouble(longlat[0]), Double.parseDouble(longlat[1])});//这里是经纬度和值
            one.put("geometry", geometryOne);
            JSONObject properties = new JSONObject();
            properties.put("proName", pro);
            properties.put("tier", tier);
//            if("-Infinity".equals(runMapData.getRemake())){
//                properties.put("value", "0");
//            }else{
//
//            }
            properties.put("value", runMapData.getRemake());
            properties.put("xy",runMapData.getMapSiteXy());
            //开始颜色分类  needJude 需要分类测试的
            double needJudge = 0;
            if (fileType == 0) {
                //实测数据
                if ("无".equals(tier)) {
                    //没有修改后的数据
                    String valueTitle = runMapData.getRemake();
                    if (StringUtils.isNotEmpty(valueTitle)) {
                        needJudge = Double.parseDouble(valueTitle);
                    } else {

                    }
                } else {
                    needJudge = Double.parseDouble(tier);
                }
            } else {
                //硬件数据
                String valueTitle = runMapData.getRemake();
                if (StringUtils.isNotEmpty(valueTitle)) {
                    needJudge = Double.parseDouble(valueTitle);
                } else {

                }
            }
            if (ColorType == 0) {
                properties.put("color", GeoTool.judgeProRange(runProperty, needJudge));
            } else {
                //分5层 级别
                for (String key : changeArrayData.keySet()) {
                    List<String> valueList = changeArrayData.get(key);
                    if (valueList.contains(runMapData.getRemake())) {
                        properties.put("color", key);
                    }
                }
            }

            one.put("properties", properties);
            features.add(one);
        }
        jsonObject.put("features", features);
        return jsonObject;
    }


    /**
     * @return java.lang.String
     * @Author yangyue
     * @Description //TODO 判断应该是什么颜色
     * @Date 14:37 2020/11/2
     * @Param [runProperty, value]
     **/
    public static String judgeProRange(RunProperty runProperty, double value) {
//        定义红色区域
        String redRange = runProperty.getProRed();
        if (StringUtils.isNotEmpty(redRange)) {
            String redReulst = dealWith(redRange, value, "red");
            if ("red".equals(redReulst)) {
                return "red";
            }
        }
        String yellowRange = runProperty.getProYellow();
        if (StringUtils.isNotEmpty(yellowRange)) {
            String yellowReuslt = dealWith(yellowRange, value, "yellow");
            if ("yellow".equals(yellowReuslt)) {
                return "yellow";
            } else {
                //既然不是红又不是黄，那就只有绿
                return "green";
            }
        }
        return "green";
    }


    /**
     * @return java.util.Map<java.lang.String       ,       java.util.List       <       java.lang.String>>
     * @Author yangyue
     * @Description //TODO 将排序好的数组分成五个
     * @Date 15:27 2020/12/7
     * @Param [runMapDataArrayDistinct]
     **/
    public static Map<String, List<String>> changeArrayData(List<RunMapData> runMapDataArrayDistinct) {
        List<String> ArrayLv1 = new ArrayList<>();
        List<String> ArrayLv2 = new ArrayList<>();
        List<String> ArrayLv3 = new ArrayList<>();
        List<String> ArrayLv4 = new ArrayList<>();
        List<String> ArrayLv5 = new ArrayList<>();
        if (runMapDataArrayDistinct.size() < 5) {
            for (int i = 0; i < runMapDataArrayDistinct.size(); i++) {
                if(runMapDataArrayDistinct.get(i)==null){
                    continue;
                }
                switch (i) {
                    case 0:
                        ArrayLv1.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 1:
                        ArrayLv2.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 2:
                        ArrayLv3.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 3:
                        ArrayLv4.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 4:
                        ArrayLv5.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    default:
                        break;
                }
            }
        } else {
            for (int i = 0; i < runMapDataArrayDistinct.size(); i++) {
                if(runMapDataArrayDistinct.get(i)==null){
                    continue;
                }
                switch (i / (runMapDataArrayDistinct.size() / 5)) {
                    case 0:
                        ArrayLv1.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 1:
                        ArrayLv2.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 2:
                        ArrayLv3.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 3:
                        ArrayLv4.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    case 4:
                        ArrayLv5.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                    default:
                        ArrayLv5.add(runMapDataArrayDistinct.get(i).getRemake());
                        break;
                }
            }
        }


        Map<String, List<String>> stringListMap = new HashMap<>();
        if(ArrayLv1.size()!=0){
            stringListMap.put("蓝", ArrayLv1);
        }
        if(ArrayLv2.size()!=0){
            stringListMap.put("绿", ArrayLv2);
        }
        if(ArrayLv3.size()!=0){
            stringListMap.put("黄", ArrayLv3);
        }
        if(ArrayLv4.size()!=0){
            stringListMap.put("橙", ArrayLv4);
        }
        if(ArrayLv5.size()!=0){
            stringListMap.put("红", ArrayLv5);
        }
         
        return stringListMap;
    }

    /**
     * @return java.lang.String
     * @Author yangyue
     * @Description //TODO 判断区域
     * @Date 14:51 2020/11/2
     * @Param [proRange, doubleValue, color]
     **/
    public static String dealWith(String proRange, double doubleValue, String color) {
        String[] rangePro = proRange.split("&");
        for (int i = 0; i < rangePro.length; i++) {
            //去头去尾
            String range = rangePro[i].substring(1, rangePro[i].length() - 1);
            String[] maxMin = range.split(",");
            if ("+∞".equals(maxMin[0])) {
                //最大值
                double maxValue = Double.parseDouble(maxMin[1]);
                if (doubleValue >= maxValue) {
                    return color;
                }
            } else if ("-∞".equals(maxMin[1])) {
                //最小值
                double minValue = Double.parseDouble(maxMin[0]);
                if (doubleValue <= minValue) {
                    return color;
                }
            } else {
                //中间
                double maxValue = Double.parseDouble(maxMin[0]);
                double minValue = Double.parseDouble(maxMin[1]);
                if (maxValue > doubleValue && minValue < doubleValue) {
                    return color;
                } else {
                    return null;
                }
            }
        }
        return null;
    }


    /**
     * @return java.util.List<com.szyjjk.entity.RunMapData>
     * @Author yangyue
     * @Description //TODO 挑选出对应的属性
     * @Date 16:16 2020/10/29
     * @Param [runMapDataList, pro]
     **/
    public static List<RunMapData> runMapDataListChangePro(List<RunMapData> runMapDataList, String pro) {
        switch (pro) {
            case "TotP":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getTotp());
                }
                break;
            case "PO4":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getPo4());
                }
                break;
            case "Turbidity":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getTurbidity());
                }
                break;
            case "EnCoc":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getEncoc());
                }
                break;
            case "chlfa":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getChlfa());
                }
                break;
            case "Temp":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getTemp());
                }
                break;
            case "NH4":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getNh4());
                }
                break;
            case "SS":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getSs());
                }
                break;
            case "FColi":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getFcoli());
                }
                break;
            case "Transparence":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getTransparence());
                }
                break;
            case "KjelN":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getKjeln());
                }
                break;
            case "PH":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getPh());
                }
                break;
            case "EColi":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getEcoli());
                }
                break;
            case "BOD":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getBod());
                }
                break;
            case "oxy":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getOxy());
                }
                break;
            case "TotN":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getTotn());
                }
                break;
            case "TOC":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getToc());
                }
                break;
            case "NO3":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getNo3());
                }
                break;
            case "Salinity":
                for (RunMapData runMapData : runMapDataList) {
                    runMapData.setRemake(runMapData.getSalinity());
                }
                break;

        }
        return runMapDataList;
    }


}